<template>
  <el-row :gutter="20">
    <el-col :span="4">
      <div class="grid-content title-text"><i class="el-icon-edit"></i>在线考试平台</div>
    </el-col>
    <el-col :span="17">
      <el-menu :router="true" :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/study">学习中心</el-menu-item>
        <el-menu-item index="/exam">考试中心</el-menu-item>
        <el-menu-item index="/admin">管理中心</el-menu-item>
      </el-menu>
    </el-col>
    <el-col :span="3">
      <el-button
        v-if="!this.userLogin && !this.adminLogin"
        type="primary"
        @click="dialogFormVisible = true"
        round
      >登录</el-button>
      <div v-else>
        <el-dropdown @command="handleCommand" trigger="click">
          <span class="el-dropdown-link">
            <i class="el-icon-user-solid"></i>
            {{this.adminLogin ? "管理员：" + this.adminData.name : "学生：" + this.userData.userName}}
            <i
              class="el-icon-arrow-down el-icon--right"
            ></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="updateData">密码修改</el-dropdown-item>
            <el-dropdown-item command="logout">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-col>

    <!-- 登录对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="登录"
      :visible.sync="dialogFormVisible"
      :show-close="false"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="loginSubmit">登 录</el-button>
      </div>
    </el-dialog>

    <!-- 密码修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="密码修改"
      :visible.sync="dialogFormVisible2"
      :show-close="false"
    >
      <el-form :model="form2" :rules="rules2" ref="form2">
        <el-form-item label="旧密码" :label-width="formLabelWidth2" prop="oldPassword">
          <el-input v-model="form2.oldPassword" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth2" prop="newPassword">
          <el-input v-model="form2.newPassword" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth2" prop="newPassword2">
          <el-input v-model="form2.newPassword2" type="password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form2')">取 消</el-button>
        <el-button type="primary" @click="changeSubmit('form2')">修 改</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  name: "navigation",
  props: ["activeIndex"],
  data() {
    // 验证密码
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form2.newPassword2 !== "") {
          this.$refs.form2.validateField("newPassword2");
        }
        callback();
      }
    };
    // 验证确认密码
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form2.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      location: "http://localhost:8866",
      form: {
        username: "",
        password: "",
      },
      form2: {
        oldPassword: "",
        newPassword: "",
        newPassword2: "",
      },
      formLabelWidth: "50px",
      formLabelWidth2: "80px",
      dialogFormVisible: false,
      dialogFormVisible2: false,
      userLogin: false,
      adminLogin: false,
      userData: "",
      adminData: "",
      rules: {
        username: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
      rules2: {
        oldPassword: [
          {
            required: true,
            message: "请输入旧密码",
            trigger: "blur",
          },
        ],
        newPassword: [{ validator: validatePass, trigger: "blur" }],
        newPassword2: [{ validator: validatePass2, trigger: "blur" }],
      },
    };
  },
  created() {
    this.isLogin();
  },
  methods: {
    // 验证是否登录，随便获取登录数据
    isLogin() {
      this.axios
        .get(this.location + "/isLogin")
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            if (res.data.msg == "用户登录") {
              this.userLogin = true;
              this.userData = res.data.extend.userData;
            } else if (res.data.msg == "教师登录") {
              this.adminLogin = true;
              this.adminData = res.data.extend.adminData;
            }
          } else if (res.data.code == 200) {
            this.userData = "";
            this.adminData = "";
            this.userLogin = false;
            this.adminLogin = false;
          }
          this.$emit("adminLogin", this.adminLogin);
          this.$emit("userLogin", this.userLogin);
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 登录请求
    loginSubmit() {
      // 组装表单信息
      const data = new FormData();
      data.append("username", this.form.username);
      data.append("password", this.form.password);
      // 发送请求
      this.axios
        .post(this.location + "/login", data)
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.dialogFormVisible = false;
            this.userData = res.data.extend.userData;
            this.adminData = res.data.extend.adminData;
            if (this.userData == null || this.userData == "") {
              this.userLogin = false;
              this.adminLogin = true;
            } else {
              this.userLogin = true;
              this.adminLogin = false;
            }
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.errorMessage();
        });
    },

    // 退出请求
    logoutSubmit() {
      this.axios
        .get(this.location + "/logout")
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.userData = "";
            this.adminData = "";
            this.adminLogin = false;
            this.userLogin = false;
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
            this.dialogFormVisible = true;
          }
          this.$router.push("/");
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 下拉列表点击事件
    handleCommand(command) {
      switch (command) {
        case "logout":
          this.logoutSubmit();
          break;
        case "updateData":
          this.dialogFormVisible2 = true;
          break;
      }
    },

    // 修改密码请求
    changeSubmit(formName) {
      if (this.userLogin || this.adminLogin) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var location;
            const data = new FormData();
            if (this.userLogin) {
              location = this.location + "/user/update";
              data.append("username", this.userData.userId);
            } else {
              location = this.location + "/admin/update";
            }
            data.append("oldPassword", this.form2.oldPassword);
            data.append("password", this.form2.newPassword);
            this.axios
              .post(location, data)
              .then((res) => {
                console.log(res);
                if (res.data.code == 100) {
                  this.resetForm("form2");
                  this.$message({
                    type: "success",
                    message: res.data.msg,
                    duration: 1000,
                  });
                } else if (res.data.code == 200) {
                  this.$message({
                    type: "warning",
                    message: res.data.msg,
                    duration: 1000,
                  });
                }
              })
              .catch((err) => {
                console.error(err);
                this.errorMessage();
              });
          } else {
            return false;
          }
        });
      } else {
        this.$message({
          type: "warning",
          message: "请先登录",
          duration: 1000,
        });
        this.$router.go(0);
        this.dialogFormVisible = true;
      }
    },

    // 关闭对话框
    resetForm(formName) {
      if (formName == "form") {
        this.dialogFormVisible = false;
      } else {
        this.dialogFormVisible2 = false;
      }
      this.$refs[formName].resetFields();
    },

    // 服务器错误消息提示
    errorMessage() {
      this.$message({
        type: "error",
        message: "服务器出现问题，请稍后重新尝试",
        duration: 1000,
      });
    },
  },
};
</script>

<style>
.title-text {
  font-weight: bold;
  font-size: 25px;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>